﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using FileTransferSystem.Models;

namespace FileTransferSystem.Services
{
    /// <summary>
    /// 历史记录管理器，负责保存和读取传输历史
    /// </summary>
    public class HistoryManager
    {
        private readonly string _historyFilePath;
        private List<TransferHistory> _histories;

        /// <summary>
        /// 默认IP地址
        /// </summary>
        public string DefaultIp { get; set; } = "127.0.0.1";

        /// <summary>
        /// 默认端口号
        /// </summary>
        public int DefaultPort { get; set; } = 8888;

        /// <summary>
        /// 默认接收文件夹
        /// </summary>
        public string DefaultReceiveFolder { get; set; } = "";

        public HistoryManager()
        {
            // 跨平台路径处理
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string appFolder = Path.Combine(appDataPath, "FileTransferSystem");

            // 确保目录存在
            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }

            _historyFilePath = Path.Combine(appFolder, "history.json");
            _histories = LoadHistory();

            // 设置默认值
            if (_histories.Count > 0)
            {
                var last = _histories[^1];
                DefaultIp = last.IpAddress;
                DefaultPort = last.Port;

                // 如果是接收记录，设置默认接收文件夹
                if (!last.IsSender && !string.IsNullOrEmpty(last.FilePath))
                {
                    var fileInfo = new FileInfo(last.FilePath);
                    DefaultReceiveFolder = fileInfo.DirectoryName;
                }
            }

            // 如果没有设置默认接收文件夹，使用临时文件夹
            if (string.IsNullOrEmpty(DefaultReceiveFolder))
            {
                DefaultReceiveFolder = Path.GetTempPath();
            }
        }

        /// <summary>
        /// 加载历史记录
        /// </summary>
        private List<TransferHistory> LoadHistory()
        {
            if (!File.Exists(_historyFilePath))
                return new List<TransferHistory>();

            try
            {
                var json = File.ReadAllText(_historyFilePath);
                return JsonSerializer.Deserialize<List<TransferHistory>>(json) ?? new List<TransferHistory>();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载历史记录失败: {ex.Message}");
                return new List<TransferHistory>();
            }
        }

        /// <summary>
        /// 保存历史记录
        /// </summary>
        private void SaveHistory()
        {
            try
            {
                var json = JsonSerializer.Serialize(_histories, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_historyFilePath, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"保存历史记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加历史记录
        /// </summary>
        public void AddHistory(string ipAddress, int port, string filePath, bool isSender)
        {
            var history = new TransferHistory
            {
                IpAddress = ipAddress,
                Port = port,
                FilePath = filePath,
                IsSender = isSender,
                Timestamp = DateTime.Now
            };

            _histories.Add(history);

            // 只保留最近20条记录
            if (_histories.Count > 20)
            {
                _histories.RemoveAt(0);
            }

            SaveHistory();

            // 更新默认值
            DefaultIp = ipAddress;
            DefaultPort = port;

            // 如果是接收记录，更新默认接收文件夹
            if (!isSender && !string.IsNullOrEmpty(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                DefaultReceiveFolder = fileInfo.DirectoryName;
            }
        }

        /// <summary>
        /// 显示历史记录
        /// </summary>
        public void ShowHistory()
        {
            if (_histories.Count == 0)
            {
                Console.WriteLine("暂无历史记录");
                return;
            }

            Console.WriteLine("传输历史:");
            for (int i = 0; i < _histories.Count; i++)
            {
                var history = _histories[i];
                Console.WriteLine($"{i + 1}. [{history.Timestamp}] {(history.IsSender ? "发送" : "接收")} {history.FilePath} 到 {history.IpAddress}:{history.Port}");
            }
        }

        /// <summary>
        /// 获取历史记录列表
        /// </summary>
        public List<TransferHistory> GetHistories()
        {
            return _histories;
        }
    }
}